#include "player.h"

const qreal Player::m_speed = 5.0;

Player::Player() : QObject()
{
    m_x = 300.0;
    m_y = 300.0;
    m_angle = 0.0;
    m_angleInRads = 0.0;

    m_isReadyToFire = true;

    m_reloadTimer = new QTimer(this);

    m_pixmap = QPixmap(tr("img/player.png"));
}

Player::~Player()
{

}

void Player::draw(QPainter *painter)
{
    painter->translate(m_x, m_y);
    painter->rotate(m_angle);
    painter->drawPixmap(-m_pixmap.width() / 2.0, -m_pixmap.height() / 2.0, m_pixmap);
    painter->resetTransform();
}

void Player::move(qreal dx, qreal dy, qint32 width, qint32 height)
{
    m_x = std::max(m_pixmap.width() / 2.0, std::min(width - m_pixmap.width() / 2.0, m_x + dx * m_speed));
    m_y = std::max(m_pixmap.height() / 2.0, std::min(height - m_pixmap.height() / 2.0, m_y + dy * m_speed));
}

void Player::rotate(qint32 toX, qint32 toY)
{
    m_angleInRads = atan2(toY - m_y, toX - m_x);
    m_angle = m_angleInRads <= 0.0
            ? m_angleInRads * 180.0 / 3.14159265359
            : m_angleInRads * 180.0 / 3.14159265359 - 360.0;
}

Bullet *Player::fire()
{
    if (m_isReadyToFire)
    {
        m_isReadyToFire = false;
        m_reloadTimer->singleShot(100, this, SLOT(reload()));
        return new Bullet(
                    m_x + m_pixmap.width() / 2.0 * cos(m_angleInRads),
                    m_y + m_pixmap.width() / 2.0 * sin(m_angleInRads),
                    cos(m_angleInRads),
                    sin(m_angleInRads)
                    );
    }
    return nullptr;
}

bool Player::intersects(Asteroid *asteroid)
{
    qreal ax = asteroid->getX();
    qreal ay = asteroid->getY();
    qreal rad = asteroid->getRadius();
    return sqrt((ax - m_x) * (ax - m_x) + (ay - m_y) * (ay - m_y)) < rad + m_pixmap.height() / 2.0;
}

void Player::reload()
{
    m_isReadyToFire = true;
}
